import json
import time
import threading
import datetime

import requests


class TTimerTask:
    def __init__(self):
        self.duration = 1
        self.lastTime = 0
        self.runTime = 0
    def execute (self):
        try:
            pass
        except Exception as er:
            print(er)
            
class TTimeTask_LiyangPower(TTimerTask):
    def __init__(self):
        super().__init__()
        self.apiUrl = "http://127.0.0.1:10081/zn/getLiyangPowersBJ?y={y}&m={m}&d={d}&h={h}"
        #self.postApi="http://hh.hhdata.cn:31563/zn/varPost"
        self.postApi = "http://127.0.0.1:10081/zn/varPost"
        self.map=[
            {
                "varId": "1159",
                "varCode": "year_down",
                "unit":"kWh"
            }, {
                "varId": "1160",
                "varCode": "year_up",
                "unit":"kWh"
            }, {
                "varId": "1161",
                "varCode": "year_generate",
                "unit":"kWh"
            }, {
                "varId": "1162",
                "varCode": "year_used"
            }, {
                "varId": "1163",
                "varCode": "month_down",
                "unit":"kWh"
            }, {
                "varId": "1164",
                "varCode": "month_up",
                "unit":"kWh"
            }, {
                "varId": "1165",
                "varCode": "month_generate",
                "unit":"kWh"
            }, {
                "varId": "1166",
                "varCode": "month_used",
                "unit":"kWh"
            }, {
                "varId": "1167",
                "varCode": "month_totalPf",
                "unit":""
            }, {
                "varId": "1168",
                "varCode": "day_down",
                "unit":"kWh"
            }, {
                "varId": "1169",
                "varCode": "day_up",
                "unit":"kWh"
            }, {
                "varId": "1170",
                "varCode": "day_generate",
                "unit":"kWh"
            }, {
                "varId": "1171",
                "varCode": "day_used",
                "unit":"kWh"
            }]

    def execute (self):
        try:
            dt = datetime.datetime.now() + datetime.timedelta(hours=1)
            staticDatetime = datetime.datetime( dt.year , dt.month , dt.day , dt.hour )
            psDt = {
                "y": staticDatetime.year ,
                "m": staticDatetime.month ,
                "d":staticDatetime.day ,
                "h": staticDatetime.hour
            }
            url = self.apiUrl.format(**psDt)

            resp = requests.get(url)
            data = json.loads(resp.text)
            print(data)
            flag = data['status'] == 1 and 'static' in data.keys()
            if flag :
                staticValues ={}
                for tk in data["static"].keys():
                    for ik in data['static'][tk].keys():
                        vk = tk +'_'+ ik
                        staticValues[vk] = data['static'][tk][ik]
                print(staticValues)

            postData = {
                "vars": []
            }
            for m in self.map:
                try:
                    varId = str( m['varId'])
                    staticKey = m['varCode']
                    if staticKey in staticValues.keys():
                        staticValue = staticValues[staticKey]
                        unit = m['unit']
                        item =  {
                            'k': 'var$'+ varId,
                            'id': varId ,
                            't': time.time() ,
                            'v': staticValue,
                            'v0': staticValue,
                            'd': str(staticValue )+ ' '+unit,
                            'regs': []
                        }
                        postData['vars'].append(item)
                except Exception as erItem:
                    print(erItem)
            try:
                headers = {
                    'Content-Type': 'application/json',
                }
                resp = requests.post(url=self.postApi, headers=headers, json=postData)
                if resp.status_code == 200:
                    print('post time static succes')
                else:
                    print('post data faild.')
            except Exception as eerr:
                print('disconnect ')
                print(eerr)
        except Exception as er:
            print(er)
    def getStaticResult(self , tm ):
        res = {}
        status = 0
        try:
            status = 0

        except Exception as er :
            print(er)
        return status , res
            
class TTimer:
    def __init__(self):
        self.tasks = []
        self.handlerThread = None
        self.isRunning = False
    def loadTasks(self):
        try:
            self.tasks=[]

            liyangCalu = TTimeTask_LiyangPower()
            liyangCalu.duration = 900
            self.tasks.append(liyangCalu)

        except Exception as er :
            print(er)
    def start(self):
        try:
            self.loadTasks()
            self.stop()
            self.isRunning = True
            self.handlerThread = threading.Thread( target=self.handler, daemon= True)
            self.handlerThread.start()
        except Exception as er :
            print(er)
    def stop(self):
        try:
            if self.isRunning :
                self.isRunning = False
        except Exception as er :
            print(er)
    def handler(self):
        try:
            while self.isRunning:
                try:
                    time.sleep(1)
                    for task in self.tasks:
                        try:
                            nowTm = time.time()
                            dltTm = nowTm - task.lastTime
                            flag = dltTm > task.duration
                            if flag :
                                task.lastTime = nowTm
                                task.execute()
                        except Exception as eee:
                            print(eee)
                except Exception as er :
                    print(er)
            self.stop()
        except Exception as er :
            print(er)


taskTimer = TTimer()